package com.hrp.book.net

import android.annotation.SuppressLint
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.KeyManagementException
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager


object ApiService {

    private const val DEFAULT_TIME_OUT = 10L
    private const val BASE_URL = "https://www.baidu.com/"

    private val logging: HttpLoggingInterceptor = HttpLoggingInterceptor()


    private val retrofit: Retrofit by lazy {
        logging.level = HttpLoggingInterceptor.Level.BODY
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
            .connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) //写操作 超时时间
            .readTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS) //读操作超时时间
            .addInterceptor(logging)
            .sslSocketFactory(getSSLSocketFactory(), ShuApiX509TrustManager())
        Retrofit.Builder()
            .client(builder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .baseUrl(BASE_URL)
            .build()
    }

    @Throws(NoSuchAlgorithmException::class, KeyManagementException::class)
    private fun getSSLSocketFactory(): SSLSocketFactory {
        val context = SSLContext.getInstance("TLS")
        val trustManagers = arrayOf<TrustManager>(ShuApiX509TrustManager())
        context.init(null, trustManagers, SecureRandom())
        return context.socketFactory
    }

    @SuppressLint("CustomX509TrustManager")
    private class ShuApiX509TrustManager : X509TrustManager {
        @SuppressLint("TrustAllX509TrustManager")
        @Throws(CertificateException::class)
        override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {

        }

        @SuppressLint("TrustAllX509TrustManager")
        @Throws(CertificateException::class)
        override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
        }

        override fun getAcceptedIssuers(): Array<X509Certificate> {
            return arrayOf()
        }
    }

    fun <T> create(service: Class<T>): T {
        return retrofit.create(service)
    }

}